package com.lagou.wang.dao.classes;

import com.lagou.wang.pojo.Class;
import com.lagou.wang.pojo.Student;
import com.lagou.wang.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class ClassDaoImpl implements ClassDao {
    @Override
    public List<Class> queryAllClass() {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from t_class";

        try {
            List<Class> classList = qr.query(sql, new BeanListHandler<Class>(Class.class));
            return classList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addClass(Class clazz) {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        String sql = "insert into t_class values (?,?,?,?,?,?)";

        Object[] param = {clazz.getCid(), clazz.getClassName(), clazz.getGrade(), clazz.getTeacher(), clazz.getSlogan(), clazz.getSize()};

        try {
            int i = qr.update(sql, param);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateClassById(Class clazz) {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        String sql = "update t_class set className=?,grade=?,teacher=?,slogan=?,size=? where cid=?";
        Object[] param = {clazz.getClassName(),clazz.getGrade(),clazz.getTeacher(),clazz.getSlogan(),clazz.getSize(),clazz.getCid()};

        try {
            int i = qr.update(sql, param);
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int deleteClassById(int cid) {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        String sql = "delete from t_class where cid = ?";

        Object param = cid;
        try {
            int i = qr.update(sql, param);
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Class queryClassById(int id) {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from t_class where cid=?";
        Object param = id;
        try {
            Class clazz = qr.query(sql, new BeanHandler<Class>(Class.class),param);
            return clazz;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}